import { useEffect, useState } from 'react'
import { get } from '@/utils/request'
// 自定义的 useFetchData
const useFetchData = (url, params = {}) => {
  const [data, setData] = useState({})
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(false)

  useEffect(() => {
    fetchData()
  }, [url, JSON.stringify(params)])

  // 获取数据
  const fetchData = async () => {
    setLoading(true)
    try {
      const { data } = await get(url, params)
      setData(data)
    } catch (err) {
      setError(true)
    } finally {
      setLoading(false)
    }
  }

  // 重新获取数据
  const onReload = async () => {
    setError(false)
    await fetchData()
  }

  return { data, loading, error, onReload }
}

export default useFetchData
